package org.pybaldaj.util;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

public class FileLinesIterator implements Iterable<String> {
	private BufferedReader reader;

	public FileLinesIterator(BufferedReader reader) throws IOException {
		this.reader = reader;
	}
	
	public FileLinesIterator(String fileName) throws IOException {
		reader = new BufferedReader(new FileReader(fileName));
	}

	@Override
	protected void finalize() throws Throwable {
		reader.close();
	}

	@Override
	public Iterator<String> iterator() {
		return new Iterator<String>() {
			private String line = null;

			@Override
			public boolean hasNext() {
				try {
					line = reader.readLine();
					if (line != null) {
						return true;
					} else {
						reader.close();
						return false;
					}
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}

			@Override
			public String next() {
				return line;
			}

			@Override
			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}
}
